import router from "@/router"
const state = {
  asideCollapse: false, // 菜单是否是收缩的
  currentPath: '/', // 当前路径
  cacheList: [], // 缓存的页面信息
  labelList: []
}
const mutations = {
  // 展开/收起侧边栏
  TOGGLE_ASIDE_COLLAPSE: (state, params) => {
    state.asideCollapse = params
  },
  // 设置当前路径
  SET_CURRENT_PATH: (state, params) => {
    state.currentPath = params
  },
  // 添加缓存的页面
  ADD_CACHE: (state, params) => {
    let has = state.cacheList.find(item => item === params)
    if (!has) {
      state.cacheList.push(params)
    }
  },
  // 移除缓存的页面
  REMOVE_CACHE: (state, params) => {
    state.cacheList = state.filter(item => item !== params)
  },
  // 添加标签
  ADD_LABEL: (state, params) => {
    let has = state.labelList.find(item => item.path === params.path)
    if (!has) {
      params.path !== '/home' && state.labelList.push(params)
      params.path === '/home' && state.labelList.unshift(params)
    }
  },
  // 移除标签
  REMOVE_LABEL: (state, params) => {
    let index = 
      state.labelList.findIndex(item => item.path === params.path)
    state.labelList.splice(index, 1)
    // 删除当前标签页之后，如果后面有打开的标签页则定位到后面一个，否则定位到前一个
    let curIndex = 0
    if (index > state.labelList.length - 1) {
      curIndex = index - 1
    } else {
      curIndex = index
    }
    let target = 
      state.labelList[curIndex]
    router.push({ path: target.path })
    // 同时把对应页面的缓存去掉
    state.cacheList = state.cacheList.filter(item => item !== params.name)
  }
}
const actions = {};
export default {
  namespaced: true,
  state,
  mutations,
  actions
}